//
//  LoginViewController.m
//  iOS-CtrlV
//
//  Created by Wang Li on 12-12-19.
//  Copyright (c) 2012年 Wang Li. All rights reserved.
//

#import "LoginViewController.h"
#import "AppDelegate.h"
#import "RegisterViewController.h"
#import "ASIFormDataRequest.h"
#import "stringAddition.h"
#import "CJSONDeserializer.h"
#import "MainTabBarController.h"
#import "WebViewController.h"
#import "ForgotPasswordViewController.h"

@interface LoginViewController ()

@end

@implementation LoginViewController
@synthesize pushtype;

- (id)init
{
    if (self = [super init]) {
        // Custom initialization
        _AppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
    }
    return self;
}

-(void) dealloc
{
    [self hudWasHidden:nil];
    [_PasswordInputField resignFirstResponder];
    [_PasswordInputField release];
    [_EmailInputField resignFirstResponder];
    [_EmailInputField release];
    [_LoginTableView release];
    [_RegBttBarItem release];
    [_BackBttBarItem release];
    [_titleBttBarItem release];
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.view setBackgroundColor:[UIColor colorWithRed:193/255.f green:193/255.f blue:193/255.f alpha:1]];
	// Do any additional setup after loading the view.


    _titleBttBarItem =[[MainTabBarController setTitle:@"登录"] retain];
    
    _BackBttBarItem = [UIButton buttonWithType:UIButtonTypeCustom];
    _BackBttBarItem.frame = CGRectMake(5, 7, 50, 30);
    [_BackBttBarItem setBackgroundImage:[UIImage imageNamed:@"button_back.png"] forState:UIControlStateNormal];
    [_BackBttBarItem setTitle:@"返回" forState:UIControlStateNormal];
    [_BackBttBarItem setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _BackBttBarItem.titleLabel.font = [UIFont systemFontOfSize:13.0f];
    [_BackBttBarItem addTarget:self action:@selector(navBackBtt) forControlEvents:UIControlEventTouchUpInside];
    [_BackBttBarItem retain];
    

    _RegBttBarItem = [UIButton buttonWithType:UIButtonTypeCustom];
    _RegBttBarItem.frame = CGRectMake(self.navigationController.navigationBar.frame.size.width-55, 7, 50, 30);
    [_RegBttBarItem setBackgroundImage:[UIImage imageNamed:@"button_right.png"] forState:UIControlStateNormal];
    [_RegBttBarItem setTitle:@"注册" forState:UIControlStateNormal];
    [_RegBttBarItem setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _RegBttBarItem.titleLabel.font = [UIFont systemFontOfSize:13.0f];
    [_RegBttBarItem addTarget:self action:@selector(registerBtt) forControlEvents:UIControlEventTouchUpInside];
    [_RegBttBarItem retain];
    
    
    _LoginTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, self.view.frame.size.height-44) style:UITableViewStyleGrouped];
    _LoginTableView.delegate = self;
    _LoginTableView.dataSource = self;
    [self.view addSubview:_LoginTableView];
    
    [_LoginTableView setBackgroundColor:BACKGROUND_COLOR];
    [_LoginTableView setBackgroundView:nil];
    
    _EmailInputField = [[UITextField alloc] initWithFrame:CGRectMake(54, 12, 250, 30)];
    _PasswordInputField = [[UITextField alloc] initWithFrame:CGRectMake(54, 12, 250, 30)];
    _PasswordInputField.secureTextEntry =YES;
    
    _EmailInputField.returnKeyType =UIReturnKeyDone;
    _PasswordInputField.returnKeyType =UIReturnKeyDone;
    
    _EmailInputField.delegate = self;
    _PasswordInputField.delegate = self;
}

-(void) viewWillDisappear:(BOOL)animated
{
    [_BackBttBarItem removeFromSuperview];
    [_RegBttBarItem removeFromSuperview];
    [_titleBttBarItem removeFromSuperview];
}

-(void) viewWillAppear:(BOOL)animated
{
    if ([_titleBttBarItem superview] == nil) {
        [self.navigationController.navigationBar addSubview:_titleBttBarItem];
    }
    if ([_BackBttBarItem superview] == nil) {
        [self.navigationController.navigationBar addSubview:_BackBttBarItem];
    }
    if ([_RegBttBarItem superview] == nil) {
        [self.navigationController.navigationBar addSubview:_RegBttBarItem];
    }
    NSUserDefaults* tUserDef = [NSUserDefaults standardUserDefaults];
    if ([tUserDef objectForKey:@"huikaoaccount"] != nil) {
        _EmailInputField.text =[tUserDef objectForKey:@"huikaoaccount"];
    }
}
//退出
-(void) navBackBtt
{
    if (self.pushtype == 0) {
        MainTabBarController* tMainTabController = (MainTabBarController*)self.navigationController.tabBarController;
        
        if (tMainTabController.mainselectedIndex == 2) {
            tMainTabController.selectedIndex = 0;
        }else{
             tMainTabController.selectedIndex =  tMainTabController.mainselectedIndex;
        }
        NSLog(@"tMainTabController.mainselectedIndex = %d",tMainTabController.mainselectedIndex);
    }

    [self.navigationController popViewControllerAnimated:YES];
}
//注册
-(void) registerBtt
{
    RegisterViewController* tRegVC = [[RegisterViewController alloc] init];
    tRegVC.navigationItem.hidesBackButton =YES;
    [self.navigationController pushViewController:tRegVC animated:YES];
    [tRegVC release];
}
//登录
-(void) loginPressed
{
    NSString* tTipStr = nil;
    UIAlertView* tTipAlert = nil;
    if ([_EmailInputField.text length] == 0) {
        tTipStr =@"账号不可为空";
        tTipAlert = [[UIAlertView alloc] initWithTitle:@"提示" message:tTipStr delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles: nil];
        [tTipAlert show];
        [tTipAlert release];
    } else if ([_PasswordInputField.text length] == 0) {
        tTipStr =@"密码不可为空";
        tTipAlert = [[UIAlertView alloc] initWithTitle:@"提示" message:tTipStr delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles: nil];
        [tTipAlert show];
        [tTipAlert release];
    }else{
        [_EmailInputField resignFirstResponder];
        [_PasswordInputField resignFirstResponder];
        HttpInterfaceManager* iHttpInterface = [HttpInterfaceManager sharedManager];
        [iHttpInterface LoginRequestGet:_EmailInputField.text code:_PasswordInputField.text];
        iHttpInterface.delegate =self;
        [self addHudLoad];
    }
}
//取密码
-(void) foregetPassWord:(UIButton*)f_sender
{
    ForgotPasswordViewController* tForePWVC = [[ForgotPasswordViewController alloc] init];
    tForePWVC.hidesBottomBarWhenPushed = YES;
    tForePWVC.navigationItem.hidesBackButton =YES;
    [self.navigationController pushViewController:tForePWVC animated:YES];
    [tForePWVC release];
}




#pragma mark -
#pragma mark MBProgressHUDDelegate
- (void)hudWasHidden:(MBProgressHUD *)hud{
    _MBHUD.delegate = nil;
	[_MBHUD removeFromSuperview];
	[_MBHUD release];
	_MBHUD=nil;
}

-(void) addHudLoad{
	if (_MBHUD == nil) {
		_MBHUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
		// Add HUD to screen
		[self.navigationController.view addSubview:_MBHUD];
		// Regisete for HUD callbacks so we can remove it from the window at the right time
		_MBHUD.delegate = self;
		_MBHUD.labelText = @"请求数据中...";
		[_MBHUD show:YES];
	}
}

#pragma mark-
#pragma mark UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}
#pragma mark-
#pragma mark 代理登陆
-(void) sinaLoginFail:(ASIHTTPRequest*)request
{
    [_AppDel showWithCustomView:@"提示" detailText:@"网络错误请稍后再试!" isCue:YES delayTime:2.f];
    [self hudWasHidden:nil];
}
-(void) sinaLoginFinish:(ASIHTTPRequest*)request
{
    NSString* tStrReq =[request responseString];
    NSLog(@"%@",tStrReq);
    NSError* tError;
    NSData *jsonData = [tStrReq dataUsingEncoding:NSUTF32BigEndianStringEncoding];
    NSDictionary *tDictionary = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&tError];
    int tErrorCode= [[tDictionary objectForKey:@"errorCode"] intValue];
    if (tErrorCode == 0) {
        NSDictionary* tDataDic = [tDictionary objectForKey:@"data"];
        WebViewController* tNextVC = [[WebViewController alloc] init];
        tNextVC.m_CallString = [tDataDic objectForKey:@"callback"];
        tNextVC.m_RequestString =[tDataDic objectForKey:@"auth"];
        tNextVC.navigationItem.hidesBackButton =YES;
        tNextVC.m_BangType = 0;
        [self.navigationController pushViewController:tNextVC animated:YES];
        [tNextVC release];
    }else{
//       [_AppDel showWithCustomView:[tDictionary objectForKey:@"errorMsg"] detailText:@"" isCue:NO delayTime:2.f];
    }
    [self hudWasHidden:nil];
}
#pragma mark-
#pragma UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if(indexPath.section == 1){
        if (indexPath.row == 0) {
            [self addHudLoad];
            HttpInterfaceManager* iHttpInterface = [HttpInterfaceManager sharedManager];
            iHttpInterface.delegate = self;
            [iHttpInterface AuthorizationRequestGet:@"sina"];
        }else if (indexPath.row == 1) {
            [self addHudLoad];
            HttpInterfaceManager* iHttpInterface = [HttpInterfaceManager sharedManager];
            iHttpInterface.delegate = self;
            [iHttpInterface AuthorizationRequestGet:@"tencent"];
        }

    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return nil;
    }else if(section == 1){
        UIView* tSectionHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 80)];
        [tSectionHeaderView setBackgroundColor:[UIColor clearColor]];
        UIButton* tLoginBtt = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        tLoginBtt.frame =CGRectMake(12, 0, 141, 40);
        [tLoginBtt setTitle:@"登录" forState:UIControlStateNormal];
        [tLoginBtt.titleLabel setFont:[UIFont systemFontOfSize:15.f]];
        //[tLoginBtt.titleLabel setTextColor:[UIColor whiteColor]];
        [tLoginBtt setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [tLoginBtt setBackgroundImage:[UIImage imageNamed:@"button_yellow_s.png"] forState:UIControlStateNormal];
        [tLoginBtt setBackgroundImage:[UIImage imageNamed:@"button_yellow_s.png"] forState:UIControlStateHighlighted];
        [tLoginBtt addTarget:self action:@selector(loginPressed) forControlEvents:UIControlEventTouchUpInside];
        [tSectionHeaderView addSubview:tLoginBtt];
        
        
        UIButton* tForePWBtt = [UIButton buttonWithType:UIButtonTypeCustom];
        tForePWBtt.frame =CGRectMake(141+13+12, 0, 141, 40);
        [tForePWBtt setTitle:@"忘记密码?" forState:UIControlStateNormal];
        [tForePWBtt setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [tForePWBtt.titleLabel setFont:[UIFont systemFontOfSize:15.f]];
        [tForePWBtt setBackgroundImage:[UIImage imageNamed:@"button_gray_s.png"] forState:UIControlStateNormal];
        [tForePWBtt setBackgroundImage:[UIImage imageNamed:@"button_yellow_s.png"] forState:UIControlStateHighlighted];
        [tForePWBtt addTarget:self action:@selector(foregetPassWord:) forControlEvents:UIControlEventTouchUpInside];
        [tSectionHeaderView addSubview:tForePWBtt];
        
        
        UILabel* tUseOtherLab = [[UILabel alloc] initWithFrame:CGRectMake(20, 49, 300, 30)];
        [tUseOtherLab setBackgroundColor:[UIColor clearColor]];
        [tUseOtherLab setTextColor:[UIColor darkGrayColor]];
        [tUseOtherLab setFont:[UIFont systemFontOfSize:15.f]];
        tUseOtherLab.text =@"用其它账号登录";
        [tSectionHeaderView addSubview:tUseOtherLab];
        [tUseOtherLab release];
        return [tSectionHeaderView autorelease];
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 0;
    }else if(section == 1){
        return 80;
    }
    return 0;
}

#pragma mark-
#pragma UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString* tSStrCell = @"logincell";
    UITableViewCell* tCell = [tableView dequeueReusableCellWithIdentifier:tSStrCell];
    if (tCell == nil) {
        tCell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tSStrCell] autorelease];
    }
    int tSection = [indexPath section];
    int tRow =[indexPath row];
    for (id tSubObject in tCell.subviews) {
        if ([tSubObject isKindOfClass:[UITextField class]]) {
            [tSubObject removeFromSuperview];
        }
    }
    if (tSection == 0) {
        [tCell.textLabel setFont:[UIFont systemFontOfSize:14]];
        tCell.accessoryType = UITableViewCellAccessoryNone;
        tCell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (tRow == 0) {
            tCell.textLabel.text =@"邮箱";
            [tCell  addSubview:_EmailInputField];
        }else if(tRow == 1){
            tCell.textLabel.text =@"密码";
            [tCell  addSubview:_PasswordInputField];
        }
    }else if(tSection == 1){
        [tCell.textLabel setFont:[UIFont boldSystemFontOfSize:16]];
        tCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        tCell.selectionStyle = UITableViewCellSelectionStyleGray;
        if (tRow == 0) {
             tCell.textLabel.text =@"用微博账号登录";
        }else if(tRow == 1){
             tCell.textLabel.text =@"用QQ账号登录";
        }
    }
    tCell.backgroundColor = [UIColor whiteColor];
    return tCell;
}
#pragma mark HttpInterfaceManageDelegate
-(void)RequestResultsLogin:(NSDictionary*)dic
{
    [self hudWasHidden:nil];
     int tErrorCode= [[dic objectForKey:@"error_code"] intValue];
    if (tErrorCode == 0 ) {
        NSDictionary* dic1 = [dic objectForKey:@"data"];
        NSUserDefaults* tUserDef = [NSUserDefaults standardUserDefaults];
        if (dic1 != nil) {
            [tUserDef setObject:_EmailInputField.text forKey:@"huikaoaccount"];
            
            NSString* user_id =[dic1 objectForKey:@"user_id"];
            [tUserDef setObject:user_id forKey:@"user_id"];
            
            NSString* name = [dic1 objectForKey:@"username"];
            [tUserDef setObject:name forKey:@"username"];
            
            NSString* email =[dic1 objectForKey:@"email"];
            [tUserDef setObject:email forKey:@"email"];
            
            NSString* userurl = [dic1 objectForKey:@"avatar"] ;
            [tUserDef setObject:userurl forKey:@"avatar"];
            
            NSString* privateCod = [dic1 objectForKey:@"private_code"] ;
            [tUserDef setObject:privateCod forKey:@"private_code"];
        }

        MainTabBarController* tMainTabController = (MainTabBarController*)self.navigationController.tabBarController;
        tMainTabController.m_UserDic = [[NSDictionary alloc] initWithDictionary:dic1];
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
        [tAppDel showWithCustomView:@"提示" detailText:[dic objectForKey:@"error_msg"] isCue:YES delayTime:2.0f];
    }

}
-(void)RequestResultsAuthorizations:(NSDictionary*)dic
{
        [self hudWasHidden:nil];
    if (dic !=nil) {
        WebViewController* tNextVC = [[WebViewController alloc] init];
        tNextVC.m_CallString = [dic objectForKey:@"callback"];
        tNextVC.m_RequestString =[dic objectForKey:@"url"];
        tNextVC.navigationItem.hidesBackButton =YES;
        tNextVC.m_BangType = 0;
        [self.navigationController pushViewController:tNextVC animated:YES];
        [tNextVC release];
    }

}
-(void)RequestResultsErrer:(NSDictionary*)dic
{
    [self hudWasHidden:nil];
    AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [tAppDel showWithCustomView:@"提示" detailText:[dic objectForKey:@"error_msg"] isCue:YES delayTime:2.0f];
  
}
@end
